<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Menus extends Model
{
    //
    protected $table = 'menus';

    /**
     * 数组中的属性会被隐藏
     *
     * @var array
     */
    protected $hidden = [];


    /**
     * 获取关联到菜单的路由
     */
    public function permission()
    {
        return $this->hasOne(config('entrust.permission'), 'menu_id', 'id')->withDefault([
            'name' => ''
        ]);
    }

    public function childMenus()
    {
        return $this->hasMany('App\Models\Menus', 'pid', 'id');
    }

    public function allChildrenMenus()
    {
        return $this->childMenus()->with(['permission']);
    }

    static public function formatMenus($menustree)
    {
        foreach ($menustree as $item=>$menus){
            $menustree[$item]['icon'] = 'fa '.$menus['icon'];
            foreach ($menus['all_children_menus'] as $key=>$menu){
                $menustree[$item]['children'][$key]['id'] = $menu['id'];
                $menustree[$item]['children'][$key]['text'] = $menu['name'];
                $menustree[$item]['children'][$key]['icon'] = 'fa '.$menu['icon'];
                if($menu['permission']['name']){
                    $menustree[$item]['children'][$key]['url'] = route($menu['permission']['name']);
                }else{
                    $menustree[$item]['children'][$key]['url'] = '';
                }
                $menustree[$item]['children'][$key]['targetType'] = "iframe-tab";
                unset($menustree[$item]['all_children_menus']);
            }
        }
        return $menustree;
    }

    /**
     * @param $arr 菜单数据
     * @param int 父id
     * @param int 步进值
     * @param int 最大步进值
     * @return array|bool
     */
    static public function getMenusTree($arr, $pid = 0, $step = 0, $maxstep = 2)
    {
        global $tree;

        if ($step >= $maxstep) {
            return true;
        }

        foreach ($arr as $key => $val) {
            if ($val['pid'] == $pid) {
                $flg = str_repeat('└―', $step);
                $val['name'] = $flg . $val['name'];
                $tree[] = $val;
                self::getMenusTree($arr, $val['id'], $step + 1, $maxstep);
            }
        }
        return $tree;
    }

    static public function getMenusChildren($arr, $pid = 0, $step = 0, $maxstep = 2)
    {
        global $tree;

        if ($step >= $maxstep) {
            return true;
        }

        foreach ($arr as $key => $val) {
            if ($val['pid'] == $pid) {
                $val['name'] = $val['name'];
                $tree[] = $val;
                self::getMenusTree($arr, $val['id'], $step + 1, $maxstep);
            }
        }


        return $tree;
    }

}
